﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;
using System.Text;
using System.IO;
using HtmlAgilityPack;
using System.Web.Script.Serialization;

namespace Client
{
    public partial class Forum : System.Web.UI.MasterPage
    {
        public HttpClient client;
        string name="";
        string urlimage;
        protected void Page_Load(object sender, EventArgs e)
        {
            
            try
            {
                string i=Session["Quyen"].ToString();
                if (i == "1")
                {
                    HyperLink1.NavigateUrl = "edit.aspx";
                }
                else
                {
                    HyperLink1.NavigateUrl = "edit.aspx";
                }
                name = Session["UserName"].ToString();
                Image1.ImageUrl = Session["Avatar"].ToString();
                HyperLink1.Text = name;
                
            }
            catch (Exception ex)
            {
                name = "";
                Image1.ImageUrl = "" ;
                HyperLink1.Text = name;
            }
            client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:18796/");

            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }

        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            try
            {
                HttpResponseMessage response = client.GetAsync("api/values/?name=" + TextBox1.Text + "&pass=" + TextBox2.Text + "&yh=").Result;
                if (response.IsSuccessStatusCode)
                {
                    string a = response.Content.ReadAsStringAsync().Result;
                    if (a == "\"\"")
                    {
                        Label1.Visible = true;
                    }
                    else
                    {
                        Label1.Visible = false;
                        Session["UserName"] = TextBox1.Text;
                        name = TextBox1.Text;
                        HyperLink1.Text = name;
                        LayAvatar();
                        int i=PhanQuyen(name);
                        Session["Quyen"] = i.ToString();
                        if (i == 1)
                        {
                            HyperLink1.NavigateUrl = "edit.aspx";
                        }
                        else
                        {
                            HyperLink1.NavigateUrl = "edit.aspx";
                        }
                        //Response.Redirect("MainBlog.aspx");
                    }
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
            }
        }
        List<string> DNFB()
        {
            List<string> list = new List<string>();
            try
            {
                #region DN FaceBook
                CookieCollection cookies = new CookieCollection();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com");
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
                //Get the response from the server and save the cookies from the first request..
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                cookies = response.Cookies;

                string email = TextBox1.Text;
                string pass = TextBox2.Text;
                string getUrl = "https://www.facebook.com/login.php?login_attempt=1";
                string postData = String.Format("email={0}&pass={1}", email, pass);
                HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
                getRequest.CookieContainer = new CookieContainer();
                getRequest.CookieContainer.Add(cookies); //recover cookies First request
                getRequest.Method = WebRequestMethods.Http.Post;
                getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
                getRequest.AllowWriteStreamBuffering = true;
                getRequest.ProtocolVersion = HttpVersion.Version11;
                getRequest.AllowAutoRedirect = true;
                getRequest.ContentType = "application/x-www-form-urlencoded";

                byte[] byteArray = Encoding.ASCII.GetBytes(postData);
                getRequest.ContentLength = byteArray.Length;
                Stream newStream = getRequest.GetRequestStream(); //open connection
                newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
                newStream.Close();

                string sourceCode;
                HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
                using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
                {
                    sourceCode = sr.ReadToEnd();
                }


                String MKsDiskFile = HttpContext.Current.Server.MapPath("~/result.htm");
                StreamWriter MKoWriter = new StreamWriter(MKsDiskFile);
                MKoWriter.Write(sourceCode);
                MKoWriter.Close();

                HtmlAgilityPack.HtmlWeb webMK = new HtmlWeb();
                HtmlAgilityPack.HtmlDocument docMK = webMK.Load(HttpContext.Current.Server.MapPath("~/result.htm"));
                string MKpath = "//img[@class='_s0 headerTinymanPhoto _rw img']";

                foreach (HtmlNode link in docMK.DocumentNode.SelectNodes(MKpath))
                {
                    string a = link.Attributes["src"].Value;
                    list.Add(a);
                }
                MKpath = "//span[@class='headerTinymanName']";
                foreach (HtmlNode link in docMK.DocumentNode.SelectNodes(MKpath))
                {
                    string a = link.InnerText;
                    list.Add(a);
                }
                list.Add(email);
                list.Add(pass);
                #endregion
            }
            catch (Exception ex)
            {
                return list;
            }
            return list;
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            List<String> list = DNFB();

            try
            {
                if (list.Count == 4)
                {
                    HttpResponseMessage response = client.GetAsync("api/values/?name=" + list[1] + "&pass=" + list[3] + "&url=" + list[0] + "&yh=" + list[2]).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string a = response.Content.ReadAsStringAsync().Result;
                        if (a == "false")
                        {
                            Label1.Visible = true;
                        }
                        else
                        {
                            Label1.Visible = false;

                            Session["UserName"] = list[1];
                            Session["Avatar"] = list[0];
                            name = list[1];
                            HyperLink1.Text = name;
                            LayAvatar();
                            
                            int i = PhanQuyen(name);
                            Session["Quyen"] = i.ToString();
                            if (i == 1)
                            {
                                HyperLink1.NavigateUrl = "edit.aspx";
                            }
                            else
                            {
                                HyperLink1.NavigateUrl = "edit.aspx";
                            }
                            //Response.Redirect("MainBlog.aspx");
                        }
                    }
                }
                else
                {
                    Label1.Visible = true;
                }
            }
            catch (Exception ex)
            {

            }
        }
        private bool Authorize(string email, string pass)
        {
            bool result = false;
            string authCode = "";
            try
            {
                string queryString = String.Format("https://www.google.com/accounts/ClientLogin?accountType=HOSTED_OR_GOOGLE&Email={0}&Passwd={1}&service=cloudprint&source={2}", email, pass, "");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(queryString);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd();

                string[] split = responseContent.Split('\n');
                foreach (string s in split)
                {
                    string[] nvsplit = s.Split('=');
                    if (nvsplit.Length == 2)
                    {
                        if (nvsplit[0] == "Auth")
                        {
                            authCode = nvsplit[1];
                            result = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return result;
            }
            return result;
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            string email = TextBox1.Text;
            string pass = TextBox2.Text;
            bool a = Authorize(email, pass);
            try
            {
                if (a == true)
                {
                    HttpResponseMessage response = client.GetAsync("api/values/?name=" + email + "&pass=" + pass + "&url=http://docs.ispconfig.org/wp-content/uploads/2010/10/user-group-icon.png" + "" + "&yh=" + "").Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string b = response.Content.ReadAsStringAsync().Result;
                        if (b == "false")
                        {
                            Label1.Visible = true;
                        }
                        else
                        {
                            response = client.GetAsync("api/values/?name=" + email + "&pass=" + pass+ "&yh=" + "").Result;
                            b = response.Content.ReadAsStringAsync().Result;
                            if (b == "false")
                            {
                                Label1.Visible = true;
                            }
                            else
                            {
                                Label1.Visible = false;

                                Session["UserName"] = TextBox1.Text;
                                name = TextBox1.Text;
                                HyperLink1.Text = name;
                                LayAvatar();
                                int i = PhanQuyen(name);
                                Session["Quyen"] = i.ToString();
                                if (i == 1)
                                {
                                    HyperLink1.NavigateUrl = "edit.aspx";
                                }
                                else
                                {
                                    HyperLink1.NavigateUrl = "edit.aspx";
                                }
                            }
                            
                           // Response.Redirect("Index.aspx");
                        }
                    }
                }
                else
                {
                    Label1.Visible = true;
                }
            }
            catch (Exception ex)
            {

            }
        }
        public void LayAvatar()
        {
            HttpResponseMessage response = client.GetAsync("api/values/?name=" + name + "&id=1&id1=2").Result;
            if (response.IsSuccessStatusCode)
            {
                string a = response.Content.ReadAsStringAsync().Result;

                string[] temp = a.Split('"');
                urlimage = temp[1];
                Image1.ImageUrl = urlimage;
                Session["Avatar"] = urlimage;
            }
            else
            {

            }
        }
        public string ReturnName()
        {
            try
            {
                name = Session["UserName"].ToString();
                return (new JavaScriptSerializer()).Serialize(name);
            }
            catch(Exception ex)
            {
                return (new JavaScriptSerializer()).Serialize(name);
            }
        }
        public string Image()
        {

            return (new JavaScriptSerializer()).Serialize(urlimage);
        }
        public string Quyen()
        {
            try
            {
                string quyen = Session["Quyen"].ToString();
                return (new JavaScriptSerializer()).Serialize(quyen);
            }
            catch (Exception ex)
            {
                string quyen = "";
                return (new JavaScriptSerializer()).Serialize(quyen);
            }
            
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            try
            {
                HttpResponseMessage response = client.GetAsync("api/values/?name=" + name + "&id=1").Result;
                if (response.IsSuccessStatusCode)
                {
                    string b = response.Content.ReadAsStringAsync().Result;
                    if (b == "false")
                    {
                        Session["UserName"] = null;
                        Session["Quyen"] = null;
                        name = "";
                        Session["Avatar"] = null;
                        TextBox1.Text="";
                        TextBox2.Text = "";
                        Response.Redirect("MainBlog.aspx");
                    }
                    else
                    {
                        Session["UserName"] = null;
                        Session["Quyen"] = null;
                        name = "";
                        Session["Avatar"] = null;
                        TextBox1.Text = "";
                        TextBox2.Text = "";
                        Response.Redirect("MainBlog.aspx");
                    }
                }

            }
            catch (Exception ex)
            {

            }
        }

        protected void LinkButton2_Click1(object sender, EventArgs e)
        {
            Response.Redirect("SignUpPage.aspx");
        }
        public int PhanQuyen(string name)
        {
            int a=-1;
            try
            {
                HttpResponseMessage response = client.GetAsync("api/values/?type=" + name).Result;
                if (response.IsSuccessStatusCode)
                {
                    string b = response.Content.ReadAsStringAsync().Result;
                    string[] c = b.Split('\"');
                    a = Convert.ToInt16(c[1]);
                    
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                return a;
            }
            return a;
        }
      

        
    }
}